//
//  XGL_HomeSearchResultViewController.swift
//  XGamesLive
//
//  Created by ios on 2024/5/27.
//

import UIKit
import MJRefresh

class XGL_HomeSearchResultViewController: UIViewController,CustomNavgationBar{
    lazy var hudView: XGL_CustomHudView = XGL_CustomHudView()
    var searchItem: SearchItemView!
    var collectionView: UICollectionView!
    var videosData: [PublishData] = []
    var showDatas: [PublishData] = []
    var pageIndex: NSInteger = 1
    let header = MJRefreshNormalHeader()
    let footer = MJRefreshBackNormalFooter()
    
    var type: String?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.createCustomBackgroundView()
        self.createXglView()
        self.creatClearNavigationBar(title: "")
        self.hudView.backgroundColor = .clear
        self.hudView.hudView.backgroundColor = .clear
        self.view.addSubview(self.hudView)
        self.hudView.snp.makeConstraints { make in
            make.width.centerX.bottom.equalToSuperview()
            make.top.equalTo(PanNavibarH)
        }
        self.getPublishDataRequest()
    }
    

}

extension XGL_HomeSearchResultViewController{
    @objc private func refresh(){
        self.pageIndex = 1
        self.getPublishDataRequest()
    }
    @objc private func getMore(){
        self.getPublishDataRequest()
    }
    
    @objc private func thumbItemAction(sender: UIButton){
        sender.isSelected = !sender.isSelected
        let index = sender.tag - 2300
        self.thumbRequest(id: self.videosData[index].id, isThumb: sender.isSelected, index: index)
    }
}

extension XGL_HomeSearchResultViewController: UISearchBarDelegate{
    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        self.searchItem.pickupSearchBar()
        self.searchItem.searchBar.text = ""
        self.showDatas = self.videosData
        self.collectionView.reloadData()
    }
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        if let searchKey = searchBar.text {
            self.searchItem.searchBar.resignFirstResponder()
            self.hudView.backgroundColor = .clear
            self.hudView.hudView.backgroundColor = .clear
            self.hudView.hudView.startAnimation()
            self.view.addSubview(self.hudView)
            self.hudView.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
            self.searchRequest()
        }
    }
}

extension XGL_HomeSearchResultViewController{
    private func getPublishDataRequest(){
        PanRequestManager<XGL_RequestBaseResponse<PageModel<PublishData>>,XGL_CustomRequestError>().request(XGLPersonalRequestAPI(requestAPI: .GetPublishData(userId: nil, page: self.pageIndex, size: 20, data1: "2", pid: nil,data5: self.type))) { result in
            switch result{
            case .success(let response):
                self.hudView.dismiss()
                if let model = response.resultData{
                    if self.header.isRefreshing{
                        self.videosData = model.data
                        self.header.endRefreshing()
                        self.footer.resetNoMoreData()
                    }else if self.footer.isRefreshing{
                        self.videosData.append(contentsOf: model.data)
                        self.footer.endRefreshing()
                    }else{
                        self.videosData = model.data
                    }
                    if model.totalPages <= model.currentPage{
                        self.footer.endRefreshingWithNoMoreData()
                    }
                    self.showDatas = self.videosData
                    self.collectionView.reloadData()
                }
                break
            default:
                self.hudView.dismiss()
                break
            }
        }
    }
    
    func thumbRequest(id: String,isThumb: Bool,index: NSInteger){
        PanRequestManager<XGL_RequestBaseResponse<Response>,XGL_CustomRequestError>().request(XGLPersonalRequestAPI(requestAPI: .Handler(auditTreeDataId: id, type: 2, actionResult: isThumb))) { result in
            switch result{
            case .success(let response):
                
                break
            default:
                break
            }
        }
    }
    
    func searchRequest(){
        PanRequestManager<XGL_RequestBaseResponse<Response>,XGL_CustomRequestError>().request(CustomRequestAPI(requestAPI: .fakeRequest(strContent: self.searchItem.searchBar.text, intContent: nil))) { result in
            self.hudView.dismiss()
            switch result{
            case .success(let response):
                self.showDatas.removeAll()
                self.collectionView.reloadData()
                MXProgressHUD.hudWithText("No data was found")
                break
            default:
                break
            }
        }
    }
}

extension XGL_HomeSearchResultViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        self.showDatas.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! XGL_VideoItemCollectionViewCell
        cell.itemData = showDatas[indexPath.item]
        cell.complete = { image in
            self.collectionView.reloadItems(at: [indexPath])
        }
        cell.thumbItem.tag = indexPath.row + 2300
        cell.thumbItem.addTarget(self, action: #selector(self.thumbItemAction(sender:)), for: .touchUpInside)
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let model = self.showDatas[indexPath.row]
        if model.data4 == "1"{
            let vc = XGL_PersonalImageDetailViewController()
            vc.detailData = model
            vc.handler = {
                self.header.beginRefreshing()
            }
            self.navigationController?.pushViewController(vc)
        }else{
            let vc = XGL_PersonalVideoDetailViewController()
            vc.detailData = model
            vc.handler = {
                self.header.beginRefreshing()
            }
            self.navigationController?.pushViewController(vc)
        }
    }
}

extension XGL_HomeSearchResultViewController: WaterfallLayoutDelegate {
    func waterfallLayout(_ waterfallLayout: WaterfallLayout, heightForItemAtIndex index: Int, itemWidth: CGFloat) -> CGFloat {
        let model = showDatas[index]
        var imageUrl = ""
        if model.data4 == "2"{
            if let url = model.data7 {
                imageUrl = url
            }
        }else{
            if let url = model.data3?.components(separatedBy: ",").first{
                imageUrl = url
            }
        }
        var scale = 150.0 / 234.0
        let cache = XGL_WaterfallImageCacheManager.shared.infor
        if let imageData = cache.imageDic[imageUrl],let image = UIImage(data: imageData) {
            scale = image.size.width / image.size.height
        }
        return conversionWithScrennWidth(value: itemWidth / scale)
    }
    
    func colCountInWaterFlowLayout(_ WaterfallLayout: WaterfallLayout) -> Int { 2 }
    
    func colMarginInWaterFlowLayout(_ WaterfallLayout: WaterfallLayout) -> CGFloat { 8 }
    
    func rowMarginInWaterFlowLayout(_ WaterfallLayout: WaterfallLayout) -> CGFloat { 16 }
    
}

extension XGL_HomeSearchResultViewController{
    private func createXglView(){
        let titleText = UILabel().then { make in
            make.text = "Search Results"
            make.textColor = UIColor.white
            make.font = UIFont.pingfangSC_Semibold(fontSize: 34.0)
        }

        let waterfallLayout = WaterfallLayout()
        waterfallLayout.delegate = self
        collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: waterfallLayout)
        collectionView.register(XGL_VideoItemCollectionViewCell.self, forCellWithReuseIdentifier: "cell")
        collectionView.backgroundColor = .clear
        collectionView.delegate = self
        collectionView.dataSource = self
        
        header.setTitle("Pull down refresh", for: .idle)
        header.setTitle("Release update", for: .pulling)
        header.setTitle("Refresh...", for: .refreshing)
        header.setRefreshingTarget(self, refreshingAction: #selector(self.refresh))
        collectionView.mj_header = header
        footer.setTitle("No more data", for: .noMoreData)
        footer.setRefreshingTarget(self, refreshingAction: #selector(self.getMore))
        collectionView.mj_footer = footer
        self.view.addSubviews([titleText,self.collectionView])
        titleText.snp.makeConstraints { make in
            make.left.equalTo(15.0)
            make.top.equalTo(PanNavibarH + 15.0)
        }
        self.collectionView.snp.makeConstraints { make in
            make.centerX.width.equalToSuperview()
            make.bottom.equalToSuperview()
            make.top.equalTo(titleText.snp.bottom).offset(16.0)
        }
    }
    func creatClearNavigationBar(title: String) {
        self.navigationController?.navigationBar.barStyle = .default
        setNeedsStatusBarAppearanceUpdate()
        let backColor = UIColor.clear
        let imageIcon = imageWithName("icon_xgl_back_white")
       
        let navView = UIView().then { make in
            make.backgroundColor = backColor
        }
        let backItem = MXCustomButton().then { make in
            make.setImage(imageIcon, for: .normal)
            make.buttonSelectAction { [weak self] in
                guard let `self` = self else { return }
                self.backAction()
            }
        }
        let titleView = UILabel().then { make in
            make.textColor = UIColor.white
            make.font = UIFont.pingfangSC_Regular(fontSize: 18.0)
            make.text = title
        }
        self.searchItem = SearchItemView().then { make in
            make.searchBar.delegate = self
        }
        navView.addSubview(backItem)
        navView.addSubview(titleView)
        navView.addSubview(self.searchItem)
        self.view.addSubview(navView)
        backItem.snp.makeConstraints { make in
            make.left.equalTo(5.0)
            make.width.height.equalTo(50.0)
            make.bottom.equalTo(-3.0)
        }
        titleView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalTo(backItem)
        }
        self.searchItem.snp.makeConstraints { make in
            make.centerY.equalTo(backItem)
            make.right.equalTo(-12.0)
            make.height.equalTo(40.0)
            make.width.equalTo(40.0)
        }
        navView.snp.makeConstraints { make in
            make.centerX.top.equalToSuperview()
            make.width.equalTo(ScreenWidth)
            make.height.equalTo(PanNavibarH)
        }
    }
}
